<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/admin/user/list">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>添加用户</el-breadcrumb-item>
    </el-breadcrumb>

    <h3 style="margin: 20px 0;">添加用户</h3>

    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px" class="demo-ruleForm">
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="ruleForm.userName"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password"></el-input>
      </el-form-item>
      <el-form-item label="昵称" prop="userNick">
        <el-input v-model="ruleForm.userNick"></el-input>
      </el-form-item>

      <el-form-item label="头像" prop="headPortrait">
        <el-upload
            action="http://localhost:8888/admin/tbUser/addImg"
            name="picFile"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>


      <el-form-item label="地址" prop="address">
        <el-input v-model="ruleForm.address"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio v-model="ruleForm.gender" label="1">男</el-radio>
        <el-radio v-model="ruleForm.gender" label="2">女</el-radio>
      </el-form-item>
      <el-form-item label="邮箱" prop="userEmail">
        <el-input v-model="ruleForm.userEmail"></el-input>
      </el-form-item>
      <el-form-item label="用户电话" prop="phone">
        <el-input v-model="ruleForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="是否启用" prop="enable">
        <el-switch
            v-model="ruleForm.enable"
            active-value="1"
            inactive-value="0"
            active-color="#13ce66"
            inactive-color="#999">
        </el-switch>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        userName: '',
        userNick: '',
        password: '',
        headPortrait: '',
        address: '',
        gender: '',
        userEmail: '',
        phone: '',
        enable: 1
      },
      rules: {
        userName: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur'}
        ]
      },
      dialogImageUrl: '',
      dialogVisible: false
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert('submit!');
          let url = 'http://localhost:8888/admin/tbUser/addUser';
          console.log('url >>> ' + url);
          console.log('data >>> ');
          console.log(this.ruleForm);
          this.axios
              .create({headers: {'Authorization': localStorage.getItem('jwt')}})
              .post(url, this.ruleForm).then((response) => {
            console.log(response.data);
            if (response.data.code == 2000) {
              this.$message({
                message: '添加管理员成功！',
                type: 'success'
              });
              this.resetForm(formName);
              this.$router.push('/admin');
            } else {
              this.$message.error(response.data.message);
            }
          }).catch(function (error) {
            console.log('响应结果为失败！');
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
      //发请求告诉服务器删除文件夹里面的文件
      //得到要删除的文件名
      let fileNameItem = file.response.data;
      console.log("文件名:" + fileNameItem);
      this.axios
          .create({headers: {'Authorization': localStorage.getItem('jwt')}})
          .get("/admin/tbUser/removeImg", {
            params: {
              fileName: fileNameItem
            }
          }).then(function (response) {
        if (response.data.code === 2000) {
          console.log("服务器文件删除完成!");
        } else {
          console.log(response.data.message);
        }
      })
    },
    handlePictureCardPreview(file) {
      // this.axios.post("/admin/tbUser/addImg").then(function (response) {
      //   console.log("服务器文件删除完成!");
      // })
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    }

  }
}
</script>


<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>